package com.wangnian.batchdemo.service.impl;

import com.wangnian.batchdemo.entity.User;
import com.wangnian.batchdemo.mapper.UserMapper;
import com.wangnian.batchdemo.service.UserService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUserOneByOne(List<User> users) {
        long startTime = System.currentTimeMillis();
        //批量插入
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        try {
            for (User user : users) {
                userMapper.insertUser(user);
            }
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }
        long endTime = System.currentTimeMillis();
        log.info("一条一条插入 SQL 插入耗时: {} ms", endTime - startTime);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUserByOneSql(List<User> users) {
        long startTime = System.currentTimeMillis();
        userMapper.insertUsersByOneSql(users);
        long endTime = System.currentTimeMillis();
        log.info("合并成一条 SQL 插入耗时: {} ms", endTime - startTime);
    }
}
